# Begin preamble

import ctypes, os, sys
from ctypes import *

_int_types = (c_int16, c_int32)
if hasattr(ctypes, 'c_int64'):
    _int_types += (c_int64,)
for t in _int_types:
    if sizeof(t) == sizeof(c_size_t):
        c_ptrdiff_t = t
del t
del _int_types

class c_void(Structure):
    _fields_ = [('dummy', c_int)]

def POINTER(obj):
    p = ctypes.POINTER(obj)
    if not isinstance(p.from_param, classmethod):
        def from_param(cls, x):
            if x is None:
                return cls()
            else:
                return x
        p.from_param = classmethod(from_param)

    return p

class UserString:
    def __init__(self, seq):
        if isinstance(seq, basestring):
            self.data = seq
        elif isinstance(seq, UserString):
            self.data = seq.data[:]
        else:
            self.data = str(seq)
    def __str__(self): return str(self.data)
    def __repr__(self): return repr(self.data)
    def __int__(self): return int(self.data)
    def __long__(self): return long(self.data)
    def __float__(self): return float(self.data)
    def __complex__(self): return complex(self.data)
    def __hash__(self): return hash(self.data)

    def __cmp__(self, string):
        if isinstance(string, UserString):
            return cmp(self.data, string.data)
        else:
            return cmp(self.data, string)
    def __contains__(self, char):
        return char in self.data

    def __len__(self): return len(self.data)
    def __getitem__(self, index): return self.__class__(self.data[index])
    def __getslice__(self, start, end):
        start = max(start, 0); end = max(end, 0)
        return self.__class__(self.data[start:end])

    def __add__(self, other):
        if isinstance(other, UserString):
            return self.__class__(self.data + other.data)
        elif isinstance(other, basestring):
            return self.__class__(self.data + other)
        else:
            return self.__class__(self.data + str(other))
    def __radd__(self, other):
        if isinstance(other, basestring):
            return self.__class__(other + self.data)
        else:
            return self.__class__(str(other) + self.data)
    def __mul__(self, n):
        return self.__class__(self.data*n)
    __rmul__ = __mul__
    def __mod__(self, args):
        return self.__class__(self.data % args)

    # the following methods are defined in alphabetical order:
    def capitalize(self): return self.__class__(self.data.capitalize())
    def center(self, width, *args):
        return self.__class__(self.data.center(width, *args))
    def count(self, sub, start=0, end=sys.maxint):
        return self.data.count(sub, start, end)
    def decode(self, encoding=None, errors=None): # XXX improve this?
        if encoding:
            if errors:
                return self.__class__(self.data.decode(encoding, errors))
            else:
                return self.__class__(self.data.decode(encoding))
        else:
            return self.__class__(self.data.decode())
    def encode(self, encoding=None, errors=None): # XXX improve this?
        if encoding:
            if errors:
                return self.__class__(self.data.encode(encoding, errors))
            else:
                return self.__class__(self.data.encode(encoding))
        else:
            return self.__class__(self.data.encode())
    def endswith(self, suffix, start=0, end=sys.maxint):
        return self.data.endswith(suffix, start, end)
    def expandtabs(self, tabsize=8):
        return self.__class__(self.data.expandtabs(tabsize))
    def find(self, sub, start=0, end=sys.maxint):
        return self.data.find(sub, start, end)
    def index(self, sub, start=0, end=sys.maxint):
        return self.data.index(sub, start, end)
    def isalpha(self): return self.data.isalpha()
    def isalnum(self): return self.data.isalnum()
    def isdecimal(self): return self.data.isdecimal()
    def isdigit(self): return self.data.isdigit()
    def islower(self): return self.data.islower()
    def isnumeric(self): return self.data.isnumeric()
    def isspace(self): return self.data.isspace()
    def istitle(self): return self.data.istitle()
    def isupper(self): return self.data.isupper()
    def join(self, seq): return self.data.join(seq)
    def ljust(self, width, *args):
        return self.__class__(self.data.ljust(width, *args))
    def lower(self): return self.__class__(self.data.lower())
    def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
    def partition(self, sep):
        return self.data.partition(sep)
    def replace(self, old, new, maxsplit=-1):
        return self.__class__(self.data.replace(old, new, maxsplit))
    def rfind(self, sub, start=0, end=sys.maxint):
        return self.data.rfind(sub, start, end)
    def rindex(self, sub, start=0, end=sys.maxint):
        return self.data.rindex(sub, start, end)
    def rjust(self, width, *args):
        return self.__class__(self.data.rjust(width, *args))
    def rpartition(self, sep):
        return self.data.rpartition(sep)
    def rstrip(self, chars=None): return self.__class__(self.data.rstrip(chars))
    def split(self, sep=None, maxsplit=-1):
        return self.data.split(sep, maxsplit)
    def rsplit(self, sep=None, maxsplit=-1):
        return self.data.rsplit(sep, maxsplit)
    def splitlines(self, keepends=0): return self.data.splitlines(keepends)
    def startswith(self, prefix, start=0, end=sys.maxint):
        return self.data.startswith(prefix, start, end)
    def strip(self, chars=None): return self.__class__(self.data.strip(chars))
    def swapcase(self): return self.__class__(self.data.swapcase())
    def title(self): return self.__class__(self.data.title())
    def translate(self, *args):
        return self.__class__(self.data.translate(*args))
    def upper(self): return self.__class__(self.data.upper())
    def zfill(self, width): return self.__class__(self.data.zfill(width))

class MutableString(UserString):
    def __init__(self, string=""):
        self.data = string
    def __hash__(self):
        raise TypeError("unhashable type (it is mutable)")
    def __setitem__(self, index, sub):
        if index < 0:
            index += len(self.data)
        if index < 0 or index >= len(self.data): raise IndexError
        self.data = self.data[:index] + sub + self.data[index+1:]
    def __delitem__(self, index):
        if index < 0:
            index += len(self.data)
        if index < 0 or index >= len(self.data): raise IndexError
        self.data = self.data[:index] + self.data[index+1:]
    def __setslice__(self, start, end, sub):
        start = max(start, 0); end = max(end, 0)
        if isinstance(sub, UserString):
            self.data = self.data[:start]+sub.data+self.data[end:]
        elif isinstance(sub, basestring):
            self.data = self.data[:start]+sub+self.data[end:]
        else:
            self.data =  self.data[:start]+str(sub)+self.data[end:]
    def __delslice__(self, start, end):
        start = max(start, 0); end = max(end, 0)
        self.data = self.data[:start] + self.data[end:]
    def immutable(self):
        return UserString(self.data)
    def __iadd__(self, other):
        if isinstance(other, UserString):
            self.data += other.data
        elif isinstance(other, basestring):
            self.data += other
        else:
            self.data += str(other)
        return self
    def __imul__(self, n):
        self.data *= n
        return self

class String(MutableString, Union):

    _fields_ = [('raw', POINTER(c_char)),
                ('data', c_char_p)]

    def __init__(self, obj=""):
        if isinstance(obj, (str, unicode, UserString)):
            self.data = str(obj)
        else:
            self.raw = obj

    def __len__(self):
        return self.data and len(self.data) or 0

    def from_param(cls, obj):
        if obj is None or obj == 0:
            return cls(POINTER(c_char)())

        elif isinstance(obj, String):
            return obj

        elif isinstance(obj, str):
            return cls(obj)

        elif isinstance(obj, c_char_p):
            return obj

        elif isinstance(obj, POINTER(c_char)):
            return obj

        elif isinstance(obj, int):
            return cls(cast(obj, POINTER(c_char)))

        else:
            return String.from_param(obj._as_parameter_)
    from_param = classmethod(from_param)

def ReturnString(obj, func=None, arguments=None):
    return String.from_param(obj)


def UNCHECKED(type):
    if (hasattr(type, "_type_") and isinstance(type._type_, str)
        and type._type_ != "P"):
        return type
    else:
        return c_void_p


class _variadic_function(object):
    def __init__(self,func,restype,argtypes):
        self.func=func
        self.func.restype=restype
        self.argtypes=argtypes
    def _as_parameter_(self):

        return self.func
    def __call__(self,*args):
        fixed_args=[]
        i=0
        for argtype in self.argtypes:

            fixed_args.append(argtype.from_param(args[i]))
            i+=1
        return self.func(*fixed_args+list(args[i:]))

# End preamble

_libs = {}
_libdirs = []

# Begin loader


import os.path, re, sys, glob
import ctypes
import ctypes.util

def _environ_path(name):
    if name in os.environ:
        return os.environ[name].split(":")
    else:
        return []

class LibraryLoader(object):
    def __init__(self):
        self.other_dirs=[]

    def load_library(self,libname):
        paths = self.getpaths(libname)

        for path in paths:
            if os.path.exists(path):
                return self.load(path)

        raise ImportError("%s not found." % libname)

    def load(self,path):
        try:
            if sys.platform == 'darwin':
                return ctypes.CDLL(path, ctypes.RTLD_GLOBAL)
            else:
                return ctypes.cdll.LoadLibrary(path)
        except OSError,e:
            raise ImportError(e)

    def getpaths(self,libname):
        if os.path.isabs(libname):
            yield libname
        else:
            for path in self.getplatformpaths(libname):
                yield path

            path = ctypes.util.find_library(libname)
            if path: yield path

    def getplatformpaths(self, libname):
        return []


class DarwinLibraryLoader(LibraryLoader):
    name_formats = ["lib%s.dylib", "lib%s.so", "lib%s.bundle", "%s.dylib",
                "%s.so", "%s.bundle", "%s"]

    def getplatformpaths(self,libname):
        if os.path.pathsep in libname:
            names = [libname]
        else:
            names = [format % libname for format in self.name_formats]

        for dir in self.getdirs(libname):
            for name in names:
                yield os.path.join(dir,name)

    def getdirs(self,libname):


        dyld_fallback_library_path = _environ_path("DYLD_FALLBACK_LIBRARY_PATH")
        if not dyld_fallback_library_path:
            dyld_fallback_library_path = [os.path.expanduser('~/lib'),
                                          '/usr/local/lib', '/usr/lib']

        dirs = []

        if '/' in libname:
            dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
        else:
            dirs.extend(_environ_path("LD_LIBRARY_PATH"))
            dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))

        dirs.extend(self.other_dirs)
        dirs.append(".")
        dirs.append(os.path.dirname(__file__))

        if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
            dirs.append(os.path.join(
                os.environ['RESOURCEPATH'],
                '..',
                'Frameworks'))

        dirs.extend(dyld_fallback_library_path)

        return dirs


class PosixLibraryLoader(LibraryLoader):
    _ld_so_cache = None

    def _create_ld_so_cache(self):

        directories = []
        for name in ("LD_LIBRARY_PATH",
                     "SHLIB_PATH", 
                     "LIBPATH",
                     "LIBRARY_PATH", 
                    ):
            if name in os.environ:
                directories.extend(os.environ[name].split(os.pathsep))
        directories.extend(self.other_dirs)
        directories.append(".")
        directories.append(os.path.dirname(__file__))

        try: directories.extend([dir.strip() for dir in open('/etc/ld.so.conf')])
        except IOError: pass

        directories.extend(['/lib', '/usr/lib', '/lib64', '/usr/lib64'])

        cache = {}
        lib_re = re.compile(r'lib(.*)\.s[ol]')
        ext_re = re.compile(r'\.s[ol]$')
        for dir in directories:
            try:
                for path in glob.glob("%s/*.s[ol]*" % dir):
                    file = os.path.basename(path)

                    # Index by filename
                    if file not in cache:
                        cache[file] = path

                    # Index by library name
                    match = lib_re.match(file)
                    if match:
                        library = match.group(1)
                        if library not in cache:
                            cache[library] = path
            except OSError:
                pass

        self._ld_so_cache = cache

    def getplatformpaths(self, libname):
        if self._ld_so_cache is None:
            self._create_ld_so_cache()

        result = self._ld_so_cache.get(libname)
        if result: yield result

        path = ctypes.util.find_library(libname)
        if path: yield os.path.join("/lib",path)

# Windows

class _WindowsLibrary(object):
    def __init__(self, path):
        self.cdll = ctypes.cdll.LoadLibrary(path)
        self.windll = ctypes.windll.LoadLibrary(path)

    def __getattr__(self, name):
        try: return getattr(self.cdll,name)
        except AttributeError:
            try: return getattr(self.windll,name)
            except AttributeError:
                raise

class WindowsLibraryLoader(LibraryLoader):
    name_formats = ["%s.dll", "lib%s.dll", "%slib.dll"]

    def load_library(self, libname):
        try:
            result = LibraryLoader.load_library(self, libname)
        except ImportError:
            result = None
            if os.path.sep not in libname:
                for name in self.name_formats:
                    try:
                        result = getattr(ctypes.cdll, name % libname)
                        if result:
                            break
                    except WindowsError:
                        result = None
            if result is None:
                try:
                    result = getattr(ctypes.cdll, libname)
                except WindowsError:
                    result = None
            if result is None:
                raise ImportError("%s not found." % libname)
        return result

    def load(self, path):
        return _WindowsLibrary(path)

    def getplatformpaths(self, libname):
        if os.path.sep not in libname:
            for name in self.name_formats:
                dll_in_current_dir = os.path.abspath(name % libname)
                if os.path.exists(dll_in_current_dir):
                    yield dll_in_current_dir
                path = ctypes.util.find_library(name % libname)
                if path:
                    yield path



loaderclass = {
    "darwin":   DarwinLibraryLoader,
    "cygwin":   WindowsLibraryLoader,
    "win32":    WindowsLibraryLoader
}

loader = loaderclass.get(sys.platform, PosixLibraryLoader)()

def add_library_search_dirs(other_dirs):
    loader.other_dirs = other_dirs

load_library = loader.load_library

del loaderclass

# End loader

add_library_search_dirs([])

# Begin libraries

_libs["CoreFoundation"] = load_library("CoreFoundation")

# End libraries


Boolean = c_ubyte 

CFTypeID = c_ulong 

CFIndex = c_long 

class struct___CFString(Structure):
    pass

CFStringRef = POINTER(struct___CFString) 

CFComparisonResult = CFIndex

CFComparatorFunction = CFUNCTYPE(UNCHECKED(CFComparisonResult), POINTER(None), POINTER(None), POINTER(None)) 


class struct_anon_3(Structure):
    pass

struct_anon_3.__slots__ = [
    'location',
    'length',
]
struct_anon_3._fields_ = [
    ('location', CFIndex),
    ('length', CFIndex),
]

CFRange = struct_anon_3 

class struct___CFAllocator(Structure):
    pass

CFAllocatorRef = POINTER(struct___CFAllocator) 

CFArrayRetainCallBack = CFUNCTYPE(UNCHECKED(POINTER(None)), CFAllocatorRef, POINTER(None)) 

CFArrayReleaseCallBack = CFUNCTYPE(UNCHECKED(None), CFAllocatorRef, POINTER(None)) 

CFArrayCopyDescriptionCallBack = CFUNCTYPE(UNCHECKED(CFStringRef), POINTER(None)) 

CFArrayEqualCallBack = CFUNCTYPE(UNCHECKED(Boolean), POINTER(None), POINTER(None)) 

class struct_anon_5(Structure):
    pass

struct_anon_5.__slots__ = [
    'version',
    'retain',
    'release',
    'copyDescription',
    'equal',
]
struct_anon_5._fields_ = [
    ('version', CFIndex),
    ('retain', CFArrayRetainCallBack),
    ('release', CFArrayReleaseCallBack),
    ('copyDescription', CFArrayCopyDescriptionCallBack),
    ('equal', CFArrayEqualCallBack),
]

CFArrayCallBacks = struct_anon_5 


try:
    kCFTypeArrayCallBacks = (CFArrayCallBacks).in_dll(_libs['CoreFoundation'], 'kCFTypeArrayCallBacks')
except:
    pass

CFArrayApplierFunction = CFUNCTYPE(UNCHECKED(None), POINTER(None), POINTER(None)) 


class struct___CFArray(Structure):
    pass

CFArrayRef = POINTER(struct___CFArray) 

CFMutableArrayRef = POINTER(struct___CFArray) 


if hasattr(_libs['CoreFoundation'], 'CFArrayGetTypeID'):
    CFArrayGetTypeID = _libs['CoreFoundation'].CFArrayGetTypeID
    CFArrayGetTypeID.argtypes = []
    CFArrayGetTypeID.restype = CFTypeID


if hasattr(_libs['CoreFoundation'], 'CFArrayCreate'):
    CFArrayCreate = _libs['CoreFoundation'].CFArrayCreate
    CFArrayCreate.argtypes = [CFAllocatorRef, POINTER(POINTER(None)), CFIndex, POINTER(CFArrayCallBacks)]
    CFArrayCreate.restype = CFArrayRef


if hasattr(_libs['CoreFoundation'], 'CFArrayCreateCopy'):
    CFArrayCreateCopy = _libs['CoreFoundation'].CFArrayCreateCopy
    CFArrayCreateCopy.argtypes = [CFAllocatorRef, CFArrayRef]
    CFArrayCreateCopy.restype = CFArrayRef


if hasattr(_libs['CoreFoundation'], 'CFArrayCreateMutable'):
    CFArrayCreateMutable = _libs['CoreFoundation'].CFArrayCreateMutable
    CFArrayCreateMutable.argtypes = [CFAllocatorRef, CFIndex, POINTER(CFArrayCallBacks)]
    CFArrayCreateMutable.restype = CFMutableArrayRef


if hasattr(_libs['CoreFoundation'], 'CFArrayCreateMutableCopy'):
    CFArrayCreateMutableCopy = _libs['CoreFoundation'].CFArrayCreateMutableCopy
    CFArrayCreateMutableCopy.argtypes = [CFAllocatorRef, CFIndex, CFArrayRef]
    CFArrayCreateMutableCopy.restype = CFMutableArrayRef


if hasattr(_libs['CoreFoundation'], 'CFArrayGetCount'):
    CFArrayGetCount = _libs['CoreFoundation'].CFArrayGetCount
    CFArrayGetCount.argtypes = [CFArrayRef]
    CFArrayGetCount.restype = CFIndex


if hasattr(_libs['CoreFoundation'], 'CFArrayGetCountOfValue'):
    CFArrayGetCountOfValue = _libs['CoreFoundation'].CFArrayGetCountOfValue
    CFArrayGetCountOfValue.argtypes = [CFArrayRef, CFRange, POINTER(None)]
    CFArrayGetCountOfValue.restype = CFIndex


if hasattr(_libs['CoreFoundation'], 'CFArrayContainsValue'):
    CFArrayContainsValue = _libs['CoreFoundation'].CFArrayContainsValue
    CFArrayContainsValue.argtypes = [CFArrayRef, CFRange, POINTER(None)]
    CFArrayContainsValue.restype = Boolean


if hasattr(_libs['CoreFoundation'], 'CFArrayGetValueAtIndex'):
    CFArrayGetValueAtIndex = _libs['CoreFoundation'].CFArrayGetValueAtIndex
    CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex]
    CFArrayGetValueAtIndex.restype = POINTER(None)


if hasattr(_libs['CoreFoundation'], 'CFArrayGetValues'):
    CFArrayGetValues = _libs['CoreFoundation'].CFArrayGetValues
    CFArrayGetValues.argtypes = [CFArrayRef, CFRange, POINTER(POINTER(None))]
    CFArrayGetValues.restype = None


if hasattr(_libs['CoreFoundation'], 'CFArrayApplyFunction'):
    CFArrayApplyFunction = _libs['CoreFoundation'].CFArrayApplyFunction
    CFArrayApplyFunction.argtypes = [CFArrayRef, CFRange, CFArrayApplierFunction, POINTER(None)]
    CFArrayApplyFunction.restype = None


if hasattr(_libs['CoreFoundation'], 'CFArrayGetFirstIndexOfValue'):
    CFArrayGetFirstIndexOfValue = _libs['CoreFoundation'].CFArrayGetFirstIndexOfValue
    CFArrayGetFirstIndexOfValue.argtypes = [CFArrayRef, CFRange, POINTER(None)]
    CFArrayGetFirstIndexOfValue.restype = CFIndex


if hasattr(_libs['CoreFoundation'], 'CFArrayGetLastIndexOfValue'):
    CFArrayGetLastIndexOfValue = _libs['CoreFoundation'].CFArrayGetLastIndexOfValue
    CFArrayGetLastIndexOfValue.argtypes = [CFArrayRef, CFRange, POINTER(None)]
    CFArrayGetLastIndexOfValue.restype = CFIndex


if hasattr(_libs['CoreFoundation'], 'CFArrayBSearchValues'):
    CFArrayBSearchValues = _libs['CoreFoundation'].CFArrayBSearchValues
    CFArrayBSearchValues.argtypes = [CFArrayRef, CFRange, POINTER(None), CFComparatorFunction, POINTER(None)]
    CFArrayBSearchValues.restype = CFIndex


if hasattr(_libs['CoreFoundation'], 'CFArrayAppendValue'):
    CFArrayAppendValue = _libs['CoreFoundation'].CFArrayAppendValue
    CFArrayAppendValue.argtypes = [CFMutableArrayRef, POINTER(None)]
    CFArrayAppendValue.restype = None


if hasattr(_libs['CoreFoundation'], 'CFArrayInsertValueAtIndex'):
    CFArrayInsertValueAtIndex = _libs['CoreFoundation'].CFArrayInsertValueAtIndex
    CFArrayInsertValueAtIndex.argtypes = [CFMutableArrayRef, CFIndex, POINTER(None)]
    CFArrayInsertValueAtIndex.restype = None


if hasattr(_libs['CoreFoundation'], 'CFArraySetValueAtIndex'):
    CFArraySetValueAtIndex = _libs['CoreFoundation'].CFArraySetValueAtIndex
    CFArraySetValueAtIndex.argtypes = [CFMutableArrayRef, CFIndex, POINTER(None)]
    CFArraySetValueAtIndex.restype = None


if hasattr(_libs['CoreFoundation'], 'CFArrayRemoveValueAtIndex'):
    CFArrayRemoveValueAtIndex = _libs['CoreFoundation'].CFArrayRemoveValueAtIndex
    CFArrayRemoveValueAtIndex.argtypes = [CFMutableArrayRef, CFIndex]
    CFArrayRemoveValueAtIndex.restype = None


if hasattr(_libs['CoreFoundation'], 'CFArrayRemoveAllValues'):
    CFArrayRemoveAllValues = _libs['CoreFoundation'].CFArrayRemoveAllValues
    CFArrayRemoveAllValues.argtypes = [CFMutableArrayRef]
    CFArrayRemoveAllValues.restype = None


if hasattr(_libs['CoreFoundation'], 'CFArrayReplaceValues'):
    CFArrayReplaceValues = _libs['CoreFoundation'].CFArrayReplaceValues
    CFArrayReplaceValues.argtypes = [CFMutableArrayRef, CFRange, POINTER(POINTER(None)), CFIndex]
    CFArrayReplaceValues.restype = None


if hasattr(_libs['CoreFoundation'], 'CFArrayExchangeValuesAtIndices'):
    CFArrayExchangeValuesAtIndices = _libs['CoreFoundation'].CFArrayExchangeValuesAtIndices
    CFArrayExchangeValuesAtIndices.argtypes = [CFMutableArrayRef, CFIndex, CFIndex]
    CFArrayExchangeValuesAtIndices.restype = None


if hasattr(_libs['CoreFoundation'], 'CFArraySortValues'):
    CFArraySortValues = _libs['CoreFoundation'].CFArraySortValues
    CFArraySortValues.argtypes = [CFMutableArrayRef, CFRange, CFComparatorFunction, POINTER(None)]
    CFArraySortValues.restype = None


if hasattr(_libs['CoreFoundation'], 'CFArrayAppendArray'):
    CFArrayAppendArray = _libs['CoreFoundation'].CFArrayAppendArray
    CFArrayAppendArray.argtypes = [CFMutableArrayRef, CFArrayRef, CFRange]
    CFArrayAppendArray.restype = None


try:
    __COREFOUNDATION_CFARRAY__ = 1
except:
    pass

__CFArray = struct___CFArray



